package io.github.wppli.domain.posts.service;

import cc.jq1024.middleware.redisson.IRedissonService;
import io.github.wppli.domain.posts.model.valobj.PostsLikeCountVO;
import io.github.wppli.domain.posts.repository.IPostsRepository;
import lombok.AllArgsConstructor;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author li--jiaqiang 2025−03−11
 */
@Service
@AllArgsConstructor
public class PostsCountService implements IPostsLikeCountService{

    private final IRedissonService redisService;
    private final IPostsRepository postsRepository;

    @Override
    public void postsLikeCountConsumeSendQueue(PostsLikeCountVO postsLikeCountVO) {
        String cacheKey = "posts_likeCount_postId";
        // 通过 Redisson 客户端的 getBlockingQueue 方法获取一个阻塞队列对象 blockingQueue。
        // 这个阻塞队列用于存储 ActivitySkuStockKeyVO 类型的对象
        RBlockingQueue<PostsLikeCountVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
        // Redisson 客户端的 getDelayedQueue 方法获取一个延迟队列对象 delayedQueue
        RDelayedQueue<PostsLikeCountVO> delayedQueue = redisService.getDelayedQueue(blockingQueue);
        // strategyAwardStockKeyVO 对象将在当前时间的基础上延迟 3 秒后才会被取出
        delayedQueue.offer(postsLikeCountVO, 3, TimeUnit.SECONDS);
    }

    @Override
    public void updateOrInsertLike(Long postId, Long userId, int status) {
        postsRepository.updateOrInsertLike(postId, userId, status);
    }

    @Override
    public PostsLikeCountVO takeLikeQueueValue() throws InterruptedException {
        String cacheKey = "posts_likeCount_postId";
        RBlockingQueue<PostsLikeCountVO> destinationQueue = redisService.getBlockingQueue(cacheKey);
        return destinationQueue.poll();
    }

    @Override
    public void updatePostsLikeCount(Long postId, int adjustCount) {
        postsRepository.likePosts(postId, adjustCount);
    }
}